package com.example.namibox_book_sdk;

import android.Manifest;
import android.Manifest.permission;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.namibox.util.Utils;
import java.util.Objects;
import namibox.booksdk.NamiboxSDKManager;
import namibox.booksdk.NamiboxSDKManager.DeleteCallback;
import namibox.booksdk.NamiboxSDKManager.LoginCallback;
import namibox.booksdk.NamiboxSDKManager.LogoutCallback;
import namibox.booksdk.NamiboxSDKManager.OpenCallback;
import namibox.booksdk.downloader.DownloadInfo;
import namibox.booksdk.event.DownloadEvent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {
  String bookid = "tape1a_001002";
  String phone = "15618398706";
  TextView infoView;

  private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      if (Objects.equals(intent.getAction(), NamiboxSDKManager.ACTION_BUY)) {
//        String type = intent.getStringExtra("type");
//        String bookid = intent.getStringExtra("bookid");
//        Toast.makeText(MainActivity.this, "收到购买消息 bookid=" + bookid + "  type=" + type, Toast.LENGTH_SHORT).show();
        startActivity(new Intent(MainActivity.this, OrderActivity.class).putExtras(intent));
      }
    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EventBus.getDefault().register(this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(NamiboxSDKManager.ACTION_BUY);
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
    setContentView(R.layout.activity_main);
    infoView = findViewById(R.id.info);
    findViewById(R.id.btn1).setOnClickListener(v -> login());
    findViewById(R.id.btn2).setOnClickListener(v -> logout());
    findViewById(R.id.btn22).setOnClickListener(v -> getLoginInfo());
    findViewById(R.id.btn3).setOnClickListener(v -> openBook());
    findViewById(R.id.btn4).setOnClickListener(v -> downloadBook());
    findViewById(R.id.btn5).setOnClickListener(v -> stopDownload());
    findViewById(R.id.btn6).setOnClickListener(v -> deleteBook());
    EditText editText = findViewById(R.id.edit);
    editText.setText(bookid);
    editText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        if (s != null) {
          bookid = s.toString();
        }
      }
    });
    EditText editText2 = findViewById(R.id.edit2);
    editText2.setText(phone);
    editText2.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        if (s != null) {
          phone = s.toString();
        }
      }
    });
    if (ContextCompat.checkSelfPermission(this, permission.WRITE_EXTERNAL_STORAGE)
        == PackageManager.PERMISSION_GRANTED) {
    } else {
      ActivityCompat.requestPermissions(this,
          new String[] { permission.WRITE_EXTERNAL_STORAGE },
          1234);
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
  }

  private void login() {
    NamiboxSDKManager.getInstance().login(phone, new LoginCallback() {
      @Override
      public void onLoginSuccess() {
        infoView.setText("登录成功\nuser=" + NamiboxSDKManager.getInstance().getLoginUser());
      }

      @Override
      public void onLoginFail(String err) {
        infoView.setText("登录失败：" + err);
      }
    });
  }

  private void logout() {
    NamiboxSDKManager.getInstance().logout(new LogoutCallback() {
      @Override
      public void onLogoutSuccess() {
        infoView.setText("登出成功\nuser=" + NamiboxSDKManager.getInstance().getLoginUser());
      }

      @Override
      public void onLogoutFail(String err) {
        infoView.setText("登出失败：" + err);
      }
    });
  }

  private void getLoginInfo() {
    infoView.setText("user=" + NamiboxSDKManager.getInstance().getLoginUser());
  }

  private void openBook() {
    NamiboxSDKManager.getInstance().openBook(bookid, new OpenCallback() {
      @Override
      public void onOpenSuccess() {
        Toast.makeText(MainActivity.this, "打开成功", Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onOpenFail(int code, String err) {
        Toast.makeText(MainActivity.this,
            "打开失败：code=" + code + ", err=" + err, Toast.LENGTH_SHORT).show();
      }
    });
  }

  private void downloadBook() {
    NamiboxSDKManager.getInstance().downloadBook(bookid);
  }

  private void stopDownload() {
    NamiboxSDKManager.getInstance().stopDownload(bookid);
  }

  private void deleteBook() {
    NamiboxSDKManager.getInstance().deleteBook(bookid, new DeleteCallback() {
      @Override
      public void onStart() {

      }

      @Override
      public void onResult(boolean success) {
        Toast.makeText(MainActivity.this, success ? "删除成功" : "删除失败", Toast.LENGTH_SHORT).show();
      }
    });
  }

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void handleBookDownloadEvent(DownloadEvent event) {
    DownloadInfo di = event.downloadInfo;
    String bookId = di.key;
    String info = Utils.format("bookId=%s state=%d progress=%d speed=%f b/s", bookId, di.state, di.progress, di.speed);
    infoView.setText(info);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions,
      int[] grantResults) {
    switch (requestCode) {
      case 1234:
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 &&
            grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          // Permission is granted. Continue the action or workflow
          // in your app.
        }  else {
          // Explain to the user that the feature is unavailable because
          // the features requires a permission that the user has denied.
          // At the same time, respect the user's decision. Don't link to
          // system settings in an effort to convince the user to change
          // their decision.
        }
        return;
    }
    // Other 'case' lines to check for other
    // permissions this app might request.
  }
}